//
//  ALAppUpdateModel.m
//  FanBei
//
//  Created by 哀木涕 on 2016/12/29.
//  Copyright © 2016年 chuxiangkeji. All rights reserved.
//

#import "ALAppUpdateModel.h"
#import "ALTabBarVC.h"
#import "XQNewFeatureVC.h"
#define GetUserDefaut [[NSUserDefaults standardUserDefaults] objectForKey:@"VersionUpdateNotice"]
#define CurrentVersion [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]

@implementation ALAppUpdateModel
#pragma mark 强制更新
+ (void)checkAppUpdate{
    NSString *storeString = [NSString stringWithFormat:@"https://itunes.apple.com/lookup?id=%@",APPLEID];
    NSURL *storeURL = [NSURL URLWithString:storeString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:storeURL];
    [request setHTTPMethod:@"GET"];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        if ( [data length] > 0 && !error ) {
            // Success
            NSDictionary *appData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                // All versions that have been uploaded to the AppStore
                NSArray *versionsInAppStore = [[appData valueForKey:@"results"] valueForKey:@"version"];
                /**
                 *  以上网络请求可以改成自己封装的类
                 */
                if(![versionsInAppStore count]) {
                    NSLog(@"No versions of app in AppStore");
                    return;
                } else {
                    NSString *currentAppStoreVersion = [versionsInAppStore objectAtIndex:0];
                    if ([self versionlessthan:[GetUserDefaut isKindOfClass:[NSString class]] && GetUserDefaut ? GetUserDefaut : CurrentVersion Newer:currentAppStoreVersion])
                    {
                        NSLog(@"暂不更新");
                    }else{
                        NSLog(@"请到appstore更新%@版本",currentAppStoreVersion);
                        /**
                         *  修复问题描述
                         */
                        NSString *describeStr = [[[appData valueForKey:@"results"] valueForKey:@"releaseNotes"] objectAtIndex:0];
                        NSLog(@"修复问题描述:%@",describeStr);
                        
                        [[MyAlertView alertViewWithTitle:[NSString stringWithFormat:@"发现新版本:%@",currentAppStoreVersion] message:describeStr onBtnClicked:^(int btnIndex) {
                            
                            [self goToAppStore];
                        } cancelButtonTitle:@"现在升级" otherButtonTitles:nil] show];
                        
                    }
                }
                
            });
        }
        
    }];
}
+ (BOOL)versionlessthan:(NSString *)oldOne Newer:(NSString *)newver
{
    if ([oldOne isEqualToString:newver]) {
        return YES;
    }else{
        if ([oldOne compare:newver options:NSNumericSearch] == NSOrderedDescending)
        {
            return YES;
        }else{
            return NO;
        }
    }
    return NO;
}
+ (void)goToAppStore
{
    NSString *urlStr = [self getAppStroeUrlForiPhone];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
    exit(0);
}
+ (NSString *)getAppStroeUrlForiPhone{
    return [NSString stringWithFormat:@"https://itunes.apple.com/us/app/51fan-bei-sheng-qian95-fan/id%@?l=zh&ls=1&mt=8",APPLEID];
}


#pragma mark 选择根视图

+ (void)selectRootVC{
     NSString *lastVersion =[NSKeyedUnarchiver unarchiveObjectWithFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"version.data"]];
    if ([CurrentVersion isEqualToString:lastVersion]) {
        [UIApplication sharedApplication].keyWindow.rootViewController = [[ALTabBarVC alloc]init];
    }else{
        // 新特性控制器
        XQNewFeatureVC *newVc = [[XQNewFeatureVC alloc] initWithFeatureImagesNameArray:@[@"newfealture-1",@"newfealture-2",@"newfealture-3"]];
        [UIApplication sharedApplication].keyWindow.rootViewController = newVc;
        newVc.pageIndicatorTintColor = [UIColor grayColor];
        newVc.completeBlock = ^{
            /** Lite版本 */
            [UIApplication sharedApplication].keyWindow.rootViewController = [[ALTabBarVC alloc]init];
            [self add3DtouchBtn];
        };
        
        [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
        // 保存当前版本
        [NSKeyedArchiver archiveRootObject:CurrentVersion toFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"version.data"]];
    }
}
+ (void)add3DtouchBtn{
    if (IOS_VERSION >= 9.0) {
        
        UIApplicationShortcutIcon *icon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"nav_high"];
        UIApplicationShortcutIcon *icon2 = [UIApplicationShortcutIcon iconWithTemplateImageName:@"cgf_search"];
        UIApplicationShortcutIcon *icon3 = [UIApplicationShortcutIcon iconWithTemplateImageName:@"nav_stroll"];
        //创建快捷选项
        UIApplicationShortcutItem * item1 = [[UIApplicationShortcutItem alloc]initWithType:@"1" localizedTitle:@"返呗" localizedSubtitle:@"双重返利，惊喜不断" icon:icon userInfo:nil];
        UIApplicationShortcutItem * item2 = [[UIApplicationShortcutItem alloc]initWithType:@"2" localizedTitle:@"搜呗" localizedSubtitle:@"搜索商品，购物返利" icon:icon2 userInfo:nil];
        UIApplicationShortcutItem * item3 = [[UIApplicationShortcutItem alloc]initWithType:@"3" localizedTitle:@"分呗" localizedSubtitle:@"急你所急，快速审核" icon:icon3 userInfo:nil];
        //添加到快捷选项数组
        [UIApplication sharedApplication].shortcutItems = @[item1,item2,item3];
    }
}
@end
